package com.dao.uitil;


import org.junit.Test;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class JDBCUtil {

    //测试数据库链接情况
//    @Test
//    public void test() throws Exception {
//        System.out.println(getConnect());
//    }



    //数据库链接
    public static Connection getConnection() throws Exception {
//        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");//注：使用系统加载器ClassLoader.getSystemClassLoader()
        InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties prop = new Properties();
        prop.load(is);

        String user = prop.getProperty("user");
        String url = prop.getProperty("url");
        String password = prop.getProperty("password");
        String driverClass = prop.getProperty("driverClass");

        Class.forName(driverClass);

        Connection conn = DriverManager.getConnection(url,user,password);

        return conn;
    }

    //数据库资源的关闭
    public static void closeResource(Connection conn, PreparedStatement ps){
        try {
            if(conn !=null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if(ps !=null)
                ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void closeResource(Connection conn, PreparedStatement ps, ResultSet rs){
        try {
            if(conn !=null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if(ps !=null)
                ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if(rs !=null)
                rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
